package com.hw.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hw.dao.EmployeeDao;
import com.hw.dao.JobsDao;
import com.hw.entity.Employees;
import com.hw.entity.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/emp")
public class EmployeeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        resp.setContentType("application/json;utf-8");
        Integer page=Integer.valueOf((String)req.getParameter("page"));
        Integer size=Integer.valueOf((String)req.getParameter("size"));
        JobsDao jobsDao=new JobsDao();
        int start =(page-1)*size;
        int end=start+size;
        EmployeeDao employeeDao=new EmployeeDao();
        List<Employees> list=employeeDao.findPage(start,end);

        Map<String,Object> result=new HashMap<>();
        result.put("code",200);
        result.put("JobId",jobsDao.findAll());
        Page<Employees> page1=new Page<>();
        page1.setData(list);
        page1.setTotals(employeeDao.total());
        result.put("data",page1);
        Gson gson = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH").create();
        PrintWriter out=resp.getWriter();
        out.write(gson.toJson(result));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     req.setCharacterEncoding("utf-8");
     Enumeration<String> value=req.getParameterNames();
        EmployeeDao employeeDao=new EmployeeDao();
     String json=new String();
     while (value.hasMoreElements()){
         json=value.nextElement();
         System.out.println(json);
     }
     Employees o=new Gson().fromJson(json, Employees.class);
       employeeDao.insert(o);

    }
}
